package com.huike.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.entity.Permission;
import com.huike.mapper.PermissionMapper;
import com.huike.service.PermissionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext context;

    @Override
    public List<Permission> getAll() {
        return permissionMapper.getAll();
    }

    @Override
    public PageInfo<Permission> getPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<Permission> all = permissionMapper.getAll();
        return new PageInfo<>(all);
    }

    @Override
    public void reload() {
        Set<Permission> permissions = new HashSet<>();
        // 1.获取controller上带@RequiresPermissions的所有方法
        Map<String, Object> controllers = context.getBeansWithAnnotation(Controller.class);
        for (Object controller :
                controllers.values()) {
            Class<?> aClass = controller.getClass();
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method m :
                    declaredMethods) {
                // toDO: getAnnotation获取不到注解的问题
//                RequiresPermissions annotation = m.getAnnotation(RequiresPermissions.class);
                RequiresPermissions annotation = AnnotationUtils.findAnnotation(m, RequiresPermissions.class);
                if (annotation!=null && annotation.value().length==2){
                    Permission permission = new Permission();
                    permission.setName(annotation.value()[0]);
                    permission.setExpression(annotation.value()[1]);
                    // todo: permissions去重的问题
                    permissions.add(permission);
                }
            }
        }
        System.out.println(permissions.size());
        // 2.挨个提取注解上的信息
        // 3.拿出你原有的权限列表跟获取到的权限比较
             // 3.1 如果原有列表里没有出现exp,应该在权限中删除，并且连带删除关系
             // 3.2 如果两边都出现的表达式，进行修改或增加

    }
}
